﻿using System.Collections.Generic;
using System.Linq;
using OTE.Contract;
using OTE.Domain;
using OTE.Web.Infrastructure.Helper;
using OTE.Web.Infrastructure.Utils;
using OTE.Web.Mvc.ViewModels.Test;
using SharpArch.NHibernate;

namespace OTE.Web.Mvc.Queries.Test
{
    public class TestQuery : NHibernateQuery, ITestQuery
    {
        public List<QuestionDTO> CreateQuestionForTest(int number, int categoryId, int userId, string createdBy)
        {
            Domain.Question questionAlias = null;

            var query = Session.QueryOver(() => questionAlias);

            var viewModels = from q in query.List()
                             where q.Category.Id == categoryId
                             select new QuestionDTO()
                             {
                                 Id = q.Id,
                                 QuestionTypeId = q.QuestionTypeId,
                                 Content = q.Content
                             };

            List<QuestionDTO> res = viewModels.ToList().RandomRecord(number, false).ToList();

            return res;
        }

        public List<TestItemViewModel> GetQuestion(int pageIndex, int pageSize, int userId, ref int totalPage)
        {
            var lst = new List<TestItemViewModel>();

            Domain.Test testAlias = null;

            Domain.Answer answerAlias = null;

            var query = Session.QueryOver(() => testAlias);

            //get question
            var res = from q in query.List()
                      where q.UserId == userId
                      select new TestItemViewModel()
                        {
                            Id = q.QuestionId,
                            Content = q.Content,
                            Type = (QuestionType)q.QuestionTypeId
                        };

            var totalCount = res.ToList().Count;

            var firstResult = (pageIndex - 1) * pageSize;

            totalPage = Common.GetTotalPage(pageSize, totalCount);

            lst = res.Skip(firstResult).Take(pageSize).ToList();

            //get answer
            var queryAnswer = Session.QueryOver(() => answerAlias);
            for (var i = 0; i < lst.Count(); i++)
            {
                var item = lst[i];
                var resAnswer = from a in queryAnswer.List()
                                where a.Question.Id == item.Id
                                select new AnswerDTO()
                                           {
                                               Id = a.Id,
                                               Content = a.Content
                                           };
                lst[i].Answers = resAnswer.ToList();
            }

            return lst;
        }
    }
}